﻿using Microsoft.Win32;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Media;
using System.Text;
using System.Windows;
using GongSolutions.Wpf.DragDrop;
using System.Windows.Threading;
using System.ComponentModel;
using VoiceTestPlatform.Infrastrature;



namespace VoiceTestPlatform
{
    public class MainViewModel : ViewModelBase, IDropTarget
    {
        private SerialPort rport = null; //接收中数据串口
        private SerialPort sport = null; //发送数据串号

        private bool testMode = false; //false 为误操作 true 为 人工
        public string ModeText
        {
            get
            {
                if (testMode)
                {
                    return "测试模式:人工";
                }
                else
                {
                    return "测试模式:误操作";
                }
            }
        }


        public MainViewModel()
        {
            Init();
            InitCommands();
        }

        public void Load()
        {
            ///从配置中读取声音库中
            selectPath = Properties.Settings.Default.SoundLib;
            RaisePropertyChanged("LibPath");
            if (!string.IsNullOrEmpty(selectPath))
            {
                LoadSoundLib();
            }
        }

        #region 命令
        private void InitCommands()
        {
            OpenSerialPortCommand = new DelegateCommand(OpenSerialPortCommandAction);
            CloseSerialPortCommand = new DelegateCommand(CloseSerialPortCommandAction);
            ExcelTestCommand = new DelegateCommand(ExcelTestCommandAction);
            SoundTestCommand = new DelegateCommand(SoundTestCommandAction);
            ProjectCommand = new DelegateCommand(ProjectCommandAction);
            SendCommand = new DelegateCommand(SendCommandAction);
            OpenSendCommand = new DelegateCommand(OpenSendCommandAction);
            CloseSendCommand = new DelegateCommand(CloseSendCommandAction);
            StopRecordCommand = new DelegateCommand(StopRecordCommandAction);
            StartRecordCommand = new DelegateCommand(StartRecordCommandAction);
            PortTestCommand = new DelegateCommand(PortTestCommandAction);
            ResultToExcelCommand = new DelegateCommand(ResultToExcelCommandAcition);
            RecordCommand = new DelegateCommand(RecordCommandAction);
            RefreshSerialPortCommand = new DelegateCommand(RefreshSerialPortCommandAction);
            PlayProjectCommand = new DelegateCommand(PlayProjectCommandAction);
            StopProjectCommand = new DelegateCommand(StopProjectCommandAction);
            ClearTextCommand = new DelegateCommand(ClearTextCommandAction);
            SaveTextCommand = new DelegateCommand(SaveTextCommandAction);
            NetworkStatusCommand = new DelegateCommand(NetworkStatusCommandAction);
            ClearResultCommand = new DelegateCommand(ClearResultCommandAction);
            ArtificialCommand = new DelegateCommand(ArtificialCommandAction);
            ClearProjectCommand = new DelegateCommand(ClearProjectCommandAction);
            SatResultCommand = new DelegateCommand(SatResultCommandAction);
            PauseProjectCommand = new DelegateCommand(PauseProjectCommandAction);
            ParameterCommand = new DelegateCommand(ParameterCommandAction);
        }

        private void ParameterCommandAction(object obj)
        {
            var vm = new ParameterViewModel();
            WindowsService.ShowWindowByViewModel(vm);
        }

        private void PauseProjectCommandAction(object obj)
        {
            IsPlayProjectEnabled = true;
            IsStopProjectEnabled = false;
            IsPauseProjectEnabled = false;
            ProjectManager.PauseProject();
        }

        private void SatResultCommandAction(object obj)
        {
            const string extension = "xls";
            var fileName = "普通测试结果统计" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var dialog = new SaveFileDialog
            {
                DefaultExt = extension,
                Filter = string.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
                FilterIndex = 1,
                FileName = fileName,
            };
            if (dialog.ShowDialog() != true) return;
            try
            {
                using (var stream = dialog.OpenFile())
                {
                    // ExportExcelAll(stream, gridView);
                    var hssfworkbook = new HSSFWorkbook(); //创建文件
                    var dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                    dsi.Company = "广东美的集团公司";
                    hssfworkbook.DocumentSummaryInformation = dsi;
                    var si = PropertySetFactory.CreateSummaryInformation();
                    si.Subject = "本文件由语音测试系统导出";
                    hssfworkbook.SummaryInformation = si;
                    var sheet1 = hssfworkbook.CreateSheet("Sheet1");




                    //创建表头
                    var headerRow = sheet1.CreateRow(0);

                    var dataColumns = new List<string>() { "地域", "性别", "编号", "命令词", "距离", "角度", "噪音背景", "成功", "失败", "超时" };
                    for (var i = 0; i < dataColumns.Count(); i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(dataColumns[i]);
                    }

                    int dataindex = 1;
                    var rs = ResultManager.ResultItems.ToList().Where(x => !string.IsNullOrEmpty(x.AudioCommand));

                    //更新 参数
                    //foreach (var item in rs)
                    //{
                    //    item.DistanceText = ParameterManager.DistanceText;
                    //    item.AngelText = ParameterManager.AngelText;
                    //    item.NoiseText = ParameterManager.NoiseText;
                    //}


                    //foreach (var item in rs)
                    //{
                    //    var deRow = sheet1.CreateRow(dataindex);
                    //    dataindex++;
                    //    deRow.CreateCell(0).SetCellValue(item.TestDate);
                    //    deRow.CreateCell(1).SetCellValue(item.ResultText);
                    //    deRow.CreateCell(2).SetCellValue(item.Recognition);
                    //    deRow.CreateCell(3).SetCellValue(item.AudioCommand);
                    //    deRow.CreateCell(4).SetCellValue(item.Audio);//相关音频
                    //    deRow.CreateCell(5).SetCellValue(item.DistanceText);//距离
                    //    deRow.CreateCell(6).SetCellValue(item.AngelText);
                    //    deRow.CreateCell(7).SetCellValue(item.NoiseText);
                    //    deRow.CreateCell(8).SetCellValue(item.RecognitionTimeString);//识别用时
                    //}

                    //分类统计
                    Dictionary<string, List<TestResult>> dict = new Dictionary<string, List<TestResult>>();
                    List<TestResult> nonList = new List<TestResult>();
                    foreach (var item in rs)
                    {
                        string key = item.Audio + item.DistanceText + item.AngelText + item.NoiseText;
                        if (string.IsNullOrEmpty(key))
                        {
                            nonList.Add(item);
                        }
                        else
                        {
                            if (dict.ContainsKey(key))
                            {
                                dict[key].Add(item);
                            }
                            else
                            {
                                var templist = new List<TestResult>();
                                templist.Add(item);
                                dict.Add(key, templist);
                            }
                        }
                    }

                    foreach (var item in dict)
                    {
                        //地域	性别	编号	命令词	      距离	角度	噪音背景	成功	失败	超时
                        dataindex++;
                        var titlerow = sheet1.CreateRow(dataindex);
                        var testinfo = item.Value[0];
                        titlerow.CreateCell(0).SetCellValue(testinfo.AudioArea); //地域
                        titlerow.CreateCell(1).SetCellValue(testinfo.AudioSex); //性别
                        titlerow.CreateCell(2).SetCellValue(testinfo.AudioNo); //编号
                        titlerow.CreateCell(3).SetCellValue(testinfo.AudioCommand); //命令词
                        titlerow.CreateCell(4).SetCellValue(testinfo.DistanceText); //距离
                        titlerow.CreateCell(5).SetCellValue(testinfo.AngelText); //角度
                        titlerow.CreateCell(6).SetCellValue(testinfo.NoiseText); //噪音背景

                        //var stRow1 = sheet1.CreateRow(dataindex);
                        //stRow1.CreateCell(0).SetCellValue("成功:");
                        var sc1 = item.Value.Where(r => r.Result == Result.Success);
                        int temp1 = 0;
                        if (sc1 != null)
                        {
                            temp1 = sc1.ToList().Count;
                        }
                        titlerow.CreateCell(7).SetCellValue(temp1); //成功
                        //stRow1.CreateCell(1).SetCellValue(temp1);

                        //stRow1.CreateCell(3).SetCellValue("失败:");
                        sc1 = item.Value.Where(r => r.Result == Result.Fail);
                        temp1 = 0;
                        if (sc1 != null)
                        {
                            temp1 = sc1.ToList().Count;
                        }
                        titlerow.CreateCell(8).SetCellValue(temp1); //失败
                        //stRow1.CreateCell(4).SetCellValue(temp1);

                        // stRow1.CreateCell(6).SetCellValue("超时:");
                        sc1 = item.Value.Where(r => r.Result == Result.Timeout);
                        temp1 = 0;
                        if (sc1 != null)
                        {
                            temp1 = sc1.ToList().Count;
                        }
                        titlerow.CreateCell(9).SetCellValue(temp1); //超时
                        //stRow1.CreateCell(7).SetCellValue(temp1);
                    }


                    hssfworkbook.Write(stream); //写入文件流
                }
            }
            catch (IOException ex)
            {
                //MessageBox.Show(string.Format("文件\"{0}\"已打开，请关闭后再点击导出！\n{1}", dialog.FileName, ex.Message), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        private void ClearProjectCommandAction(object obj)
        {
            ProjectManager.ProjectItems.Clear();
        }
        private void ArtificialCommandAction(object obj)
        {
            testMode = true;
            RaisePropertyChanged("ModeText");
            var vm = new ArtificialViewModel();
            WindowsService.ShowWindowByViewModel(vm);
        }

        private void ClearResultCommandAction(object obj)
        {
            ResultManager.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
            {
                ResultManager.ResultItems.Clear();
            }));
        }

        private void NetworkStatusCommandAction(object obj)
        {
            //throw new NotImplementedException();
            var vm = new NetworkStatusViewModel();
            WindowsService.ShowWindowByViewModel(vm);
        }

        private void SaveTextCommandAction(object obj)
        {
            if (string.IsNullOrEmpty(ReceiveText))
            {
                MessageBox.Show("原消息为空");
                return;
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = ParameterManager.RunDir;
            sfd.FileName = "普通测试原消息" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            sfd.Filter = "(*.txt)|*.txt|(*.*)|*.*";
            sfd.AddExtension = true;
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == true)
            {
                //textBox2.Text = sfd.FileName;
                FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                try
                {
                    sw.Write(ReceiveText);
                    sw.Flush();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                finally
                {
                    sw.Close();
                    fs.Close();
                }
            }
        }
        private void ClearTextCommandAction(object obj)
        {
            ReceiveText = string.Empty;
        }

        private void PlayProjectCommandAction(object obj)
        {
            IsPlayProjectEnabled = false;
            IsStopProjectEnabled = true;
            IsPauseProjectEnabled = true;
            //ResultManager.ResultItems.Clear();
            ProjectManager.PlayProjectCommand.Execute(null);
        }

        private void StopProjectCommandAction(object obj)
        {
            IsPlayProjectEnabled = true;
            IsStopProjectEnabled = false;
            IsPauseProjectEnabled = false;
            ProjectManager.StopPlayProjectCommand.Execute(null);
        }

        private void RefreshSerialPortCommandAction(object obj)
        {
            SerialPorts = SerialPortHelper.Instance.GetPortNames();
        }

        private void RecordCommandAction(object obj)
        {
            testMode = false;
            RaisePropertyChanged("ModeText");
            var vm = new RecordViewModel();
            WindowsService.ShowWindowByViewModel(vm);
        }

        private void ResultToExcelCommandAcition(object obj)
        {
            const string extension = "xls";
            var fileName = "普通测试结果" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var dialog = new SaveFileDialog
            {
                DefaultExt = extension,
                Filter = string.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
                FilterIndex = 1,
                FileName = fileName,
            };
            if (dialog.ShowDialog() != true) return;
            try
            {
                using (var stream = dialog.OpenFile())
                {
                    // ExportExcelAll(stream, gridView);
                    var hssfworkbook = new HSSFWorkbook(); //创建文件
                    var dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                    dsi.Company = "广东美的集团公司";
                    hssfworkbook.DocumentSummaryInformation = dsi;
                    var si = PropertySetFactory.CreateSummaryInformation();
                    si.Subject = "本文件由语音测试系统导出";
                    hssfworkbook.SummaryInformation = si;
                    var sheet1 = hssfworkbook.CreateSheet("结果明细");




                    //创建表头
                    var headerRow = sheet1.CreateRow(0);
                    var dataColumns = new List<string>() { "时间", "结果", "识别", "音频命令", "相关音频" ,
                    "距离", "角度", "噪音背景", "识别用时"};
                    for (var i = 0; i < dataColumns.Count(); i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(dataColumns[i]);
                    }

                    int dataindex = 1;
                    var rs = ResultManager.ResultItems.ToList().Where(x => !string.IsNullOrEmpty(x.AudioCommand));

                    //更新 参数
                    //foreach (var item in rs)
                    //{
                    //    item.DistanceText = ParameterManager.DistanceText;
                    //    item.AngelText = ParameterManager.AngelText;
                    //    item.NoiseText = ParameterManager.NoiseText;
                    //}


                    foreach (var item in rs)
                    {
                        var deRow = sheet1.CreateRow(dataindex);
                        dataindex++;
                        deRow.CreateCell(0).SetCellValue(item.TestDate);
                        deRow.CreateCell(1).SetCellValue(item.ResultText);
                        deRow.CreateCell(2).SetCellValue(item.Recognition);
                        deRow.CreateCell(3).SetCellValue(item.AudioCommand);
                        deRow.CreateCell(4).SetCellValue(item.Audio);//相关音频
                        deRow.CreateCell(5).SetCellValue(item.DistanceText);//距离
                        deRow.CreateCell(6).SetCellValue(item.AngelText);
                        deRow.CreateCell(7).SetCellValue(item.NoiseText);
                        deRow.CreateCell(8).SetCellValue(item.RecognitionTimeString);//识别用时
                    }

                    //分类统计
                    Dictionary<string, List<TestResult>> dict = new Dictionary<string, List<TestResult>>();
                    List<TestResult> nonList = new List<TestResult>();
                    foreach (var item in rs)
                    {
                        string key = item.Audio;
                        if (string.IsNullOrEmpty(key))
                        {
                            nonList.Add(item);
                        }
                        else
                        {
                            if (dict.ContainsKey(key))
                            {
                                dict[key].Add(item);
                            }
                            else
                            {
                                var templist = new List<TestResult>();
                                templist.Add(item);
                                dict.Add(key, templist);
                            }
                        }
                    }

                    foreach (var item in dict)
                    {
                        dataindex++;
                        var titlerow = sheet1.CreateRow(dataindex);
                        titlerow.CreateCell(0).SetCellValue("语音命令:");
                        titlerow.CreateCell(1).SetCellValue(item.Key);
                        dataindex++;
                        var stRow1 = sheet1.CreateRow(dataindex);
                        stRow1.CreateCell(0).SetCellValue("成功:");
                        var sc1 = item.Value.Where(r => r.Result == Result.Success);
                        int temp1 = 0;
                        if (sc1 != null)
                        {
                            temp1 = sc1.ToList().Count;
                        }
                        stRow1.CreateCell(1).SetCellValue(temp1);

                        stRow1.CreateCell(3).SetCellValue("失败:");
                        sc1 = item.Value.Where(r => r.Result == Result.Fail);
                        temp1 = 0;
                        if (sc1 != null)
                        {
                            temp1 = sc1.ToList().Count;
                        }
                        stRow1.CreateCell(4).SetCellValue(temp1);

                        stRow1.CreateCell(6).SetCellValue("超时:");
                        sc1 = item.Value.Where(r => r.Result == Result.Timeout);
                        temp1 = 0;
                        if (sc1 != null)
                        {
                            temp1 = sc1.ToList().Count;
                        }
                        stRow1.CreateCell(7).SetCellValue(temp1);
                    }



                    //统计
                    dataindex++;
                    dataindex++;
                    var stRow = sheet1.CreateRow(dataindex);
                    stRow.CreateCell(0).SetCellValue("合计");
                    dataindex++;
                    stRow = sheet1.CreateRow(dataindex);
                    stRow.CreateCell(0).SetCellValue("成功:");
                    var sc = rs.Where(r => r.Result == Result.Success);
                    int temp = 0;
                    if (sc != null)
                    {
                        temp = sc.ToList().Count;
                    }
                    stRow.CreateCell(1).SetCellValue(temp);

                    stRow.CreateCell(3).SetCellValue("失败:");
                    sc = rs.Where(r => r.Result == Result.Fail);
                    temp = 0;
                    if (sc != null)
                    {
                        temp = sc.ToList().Count;
                    }
                    stRow.CreateCell(4).SetCellValue(temp);

                    stRow.CreateCell(6).SetCellValue("超时:");
                    sc = rs.Where(r => r.Result == Result.Timeout);
                    temp = 0;
                    if (sc != null)
                    {
                        temp = sc.ToList().Count;
                    }

                    stRow.CreateCell(7).SetCellValue(temp);
                    ExcelSatSheet(hssfworkbook);

                    hssfworkbook.Write(stream); //写入文件流
                }
            }
            catch (IOException ex)
            {
                //MessageBox.Show(string.Format("文件\"{0}\"已打开，请关闭后再点击导出！\n{1}", dialog.FileName, ex.Message), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        private void ExcelSatSheet(HSSFWorkbook hssfworkbook)
        {
            var sheet1 = hssfworkbook.CreateSheet("统计结果");
            //创建表头
            var headerRow = sheet1.CreateRow(0);

            var dataColumns = new List<string>() { "地域", "性别", "编号", "命令词", "距离", "角度", "噪音背景", "成功", "失败", "超时" };
            for (var i = 0; i < dataColumns.Count(); i++)
            {
                headerRow.CreateCell(i).SetCellValue(dataColumns[i]);
            }

            int dataindex = 1;
            var rs = ResultManager.ResultItems.ToList().Where(x => !string.IsNullOrEmpty(x.AudioCommand));

            //更新 参数
            //foreach (var item in rs)
            //{
            //    item.DistanceText = ParameterManager.DistanceText;
            //    item.AngelText = ParameterManager.AngelText;
            //    item.NoiseText = ParameterManager.NoiseText;
            //}



            //分类统计
            Dictionary<string, List<TestResult>> dict = new Dictionary<string, List<TestResult>>();
            List<TestResult> nonList = new List<TestResult>();
            foreach (var item in rs)
            {
                string key = item.Audio + item.DistanceText + item.AngelText + item.NoiseText;
                if (string.IsNullOrEmpty(key))
                {
                    nonList.Add(item);
                }
                else
                {
                    if (dict.ContainsKey(key))
                    {
                        dict[key].Add(item);
                    }
                    else
                    {
                        var templist = new List<TestResult>();
                        templist.Add(item);
                        dict.Add(key, templist);
                    }
                }
            }

            foreach (var item in dict)
            {
                //地域	性别	编号	命令词	      距离	角度	噪音背景	成功	失败	超时                
                var titlerow = sheet1.CreateRow(dataindex);
                dataindex++;
                var testinfo = item.Value[0];
                titlerow.CreateCell(0).SetCellValue(testinfo.AudioArea); //地域
                titlerow.CreateCell(1).SetCellValue(testinfo.AudioSex); //性别
                titlerow.CreateCell(2).SetCellValue(testinfo.AudioNo); //编号
                titlerow.CreateCell(3).SetCellValue(testinfo.AudioCommand); //命令词
                titlerow.CreateCell(4).SetCellValue(testinfo.DistanceText); //距离
                titlerow.CreateCell(5).SetCellValue(testinfo.AngelText); //角度
                titlerow.CreateCell(6).SetCellValue(testinfo.NoiseText); //噪音背景

                //var stRow1 = sheet1.CreateRow(dataindex);
                //stRow1.CreateCell(0).SetCellValue("成功:");
                var sc1 = item.Value.Where(r => r.Result == Result.Success);
                int temp1 = 0;
                if (sc1 != null)
                {
                    temp1 = sc1.ToList().Count;
                }
                titlerow.CreateCell(7).SetCellValue(temp1); //成功
                //stRow1.CreateCell(1).SetCellValue(temp1);

                //stRow1.CreateCell(3).SetCellValue("失败:");
                sc1 = item.Value.Where(r => r.Result == Result.Fail);
                temp1 = 0;
                if (sc1 != null)
                {
                    temp1 = sc1.ToList().Count;
                }
                titlerow.CreateCell(8).SetCellValue(temp1); //失败
                //stRow1.CreateCell(4).SetCellValue(temp1);

                // stRow1.CreateCell(6).SetCellValue("超时:");
                sc1 = item.Value.Where(r => r.Result == Result.Timeout);
                temp1 = 0;
                if (sc1 != null)
                {
                    temp1 = sc1.ToList().Count;
                }
                titlerow.CreateCell(9).SetCellValue(temp1); //超时
                //stRow1.CreateCell(7).SetCellValue(temp1);
            }

        }




        private void PortTestCommandAction(object obj)
        {
            //SoundManager.StartRecord();
            if (PortTestVisibility == Visibility.Collapsed)
            {
                PortTestVisibility = Visibility.Visible;
            }
            else
            {
                PortTestVisibility = Visibility.Collapsed;
            }
        }

        private void StartRecordCommandAction(object obj)
        {
            SoundManager.StartRecord();
        }

        private void StopRecordCommandAction(object obj)
        {
            SoundManager.StopRecord();
        }

        private void CloseSendCommandAction(object obj)
        {
            if (sport != null)
            {
                sport.Close();
                sport = null;
                WindowsService.ShowMessageBox("关闭发送串口成功");
            }
            IsSendPortOpening = false;
            SendOpenText = "否";

        }

        private void OpenSendCommandAction(object obj)
        {
            sport = SerialPortHelper.Instance.OpenPort(SelectedSendPort, SelectedBaudRate, SelectedDataBit, SelectedStopBit, SelectedParity);
            if (sport != null)
            {
                sport.Encoding = System.Text.Encoding.GetEncoding("UTF-8");
                IsSendPortOpening = true;
                SendOpenText = "是";
                WindowsService.ShowMessageBox("打开发送串口成功");
            }
            else
            {
                IsSendPortOpening = false;
                SendOpenText = "否";
                WindowsService.ShowMessageBox("打开发送串口失败");
            }
        }

        private void SendCommandAction(object obj)
        {
            if (string.IsNullOrEmpty(SendText))
            {
                WindowsService.ShowMessageBox("发送内容不要为空");
                return;
            }
            if (sport != null)
            {
                sport.WriteLine(SendText);
            }
            else
            {
                WindowsService.ShowMessageBox("发送串口未打开");
            }
        }
        public string LibPath
        {
            get { return selectPath; }
        }

        string selectPath;
        private void ProjectCommandAction(object obj)
        {
            //throw new Exception("dddfff");
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
            if (!string.IsNullOrEmpty(selectPath))
            {
                folderBrowserDialog.SelectedPath = selectPath;
            }
            System.Windows.Forms.DialogResult result = folderBrowserDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                selectPath = folderBrowserDialog.SelectedPath;
                RaisePropertyChanged("LibPath");
                Properties.Settings.Default.SoundLib = selectPath;
                Properties.Settings.Default.Save();

                LoadSoundLib();
            }
        }

        /// <summary>
        ///  加载音频库
        /// </summary>
        private void LoadSoundLib()
        {
            string[] sounds = Directory.GetFiles(selectPath, "*.wav", SearchOption.AllDirectories);

            if (sounds != null)
            {
                fullSoundsSource = new ObservableCollection<Sound>();
                foreach (var item in sounds)
                {
                    fullSoundsSource.Add(new Sound() { Path = item, DisplayText = Path.GetFileName(item) });
                }
                SoundsSource = fullSoundsSource;
            }
        }

        private void SoundTestCommandAction(object obj)
        {
            Microsoft.Win32.OpenFileDialog op = new Microsoft.Win32.OpenFileDialog();
            op.InitialDirectory = @"D:\";
            op.RestoreDirectory = false;
            op.Multiselect = true;
            op.Filter = "声音(*.wav)|*.wav";
            if (op.ShowDialog() == true)
            {
                string[] sounds = op.FileNames;
                using (SoundPlayer player = new SoundPlayer())
                {
                    for (int i = 0; i < sounds.Length; i++)
                    {
                        player.SoundLocation = sounds[i];
                        player.PlaySync();
                    }
                }
            }

        }

        private void CloseSerialPortCommandAction(object obj)
        {
            if (rport != null)
            {
                try
                {
                    rport.Close();
                }
                catch (Exception)
                {
                    WindowsService.ShowMessageBox("关闭串口出错");
                    return;
                }

            }
            IsPortOpening = false;
            SerialPortHelper.Instance.IsPortOpened = false;
            WindowsService.ShowMessageBox("打开关闭成功");
        }

        private void ExcelTestCommandAction(object obj)
        {
            //throw new Exception("ssss");
            const string extension = "xls";
            var fileName = "ExcelFile";
            var dialog = new SaveFileDialog
            {
                DefaultExt = extension,
                Filter = string.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
                FilterIndex = 1,
                FileName = fileName,
            };
            if (dialog.ShowDialog() != true) return;
            try
            {
                using (var stream = dialog.OpenFile())
                {
                    // ExportExcelAll(stream, gridView);
                    var hssfworkbook = new HSSFWorkbook(); //创建文件
                    var dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                    dsi.Company = "广东xx公司";
                    hssfworkbook.DocumentSummaryInformation = dsi;
                    var si = PropertySetFactory.CreateSummaryInformation();
                    si.Subject = "本文件由t系统导出";
                    hssfworkbook.SummaryInformation = si;
                    var sheet1 = hssfworkbook.CreateSheet("Sheet1");

                    //创建表头
                    var headerRow = sheet1.CreateRow(0);
                    var dataColumns = new List<string>() { "音频名", "次数", "是否循环", "c4" };
                    for (var i = 0; i < dataColumns.Count(); i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(dataColumns[i]);
                    }

                    int dataindex = 1;
                    foreach (var item in ProjectManager.ProjectItems)
                    {
                        var deRow = sheet1.CreateRow(dataindex);
                        dataindex++;
                        deRow.CreateCell(0).SetCellValue(item.DisplayText);
                        deRow.CreateCell(1).SetCellValue(item.PlayTimes.ToString());
                        deRow.CreateCell(2).SetCellValue(item.LoopText);
                    }


                    hssfworkbook.Write(stream); //写入文件流
                }
            }
            catch (IOException ex)
            {
                //MessageBox.Show(string.Format("文件\"{0}\"已打开，请关闭后再点击导出！\n{1}", dialog.FileName, ex.Message), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        private void OpenSerialPortCommandAction(object obj)
        {
            rport = SerialPortHelper.Instance.OpenPort(SelectedPort, SelectedBaudRate, SelectedDataBit, SelectedStopBit, SelectedParity);
            if (rport != null)
            {
                rport.Encoding = System.Text.Encoding.GetEncoding(SelectedEncoding);
                rport.DataReceived += rport_DataReceived;
                IsPortOpening = true;
                WindowsService.ShowMessageBox("打开串口成功");
                SerialPortHelper.Instance.IsPortOpened = true;
            }
            else
            {
                WindowsService.ShowMessageBox("打开串口失败");
            }
        }

        void rport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(100);//延时100ms等待接收完数据
            string r;
            try
            {
                r = rport.ReadExisting();
            }
            catch (Exception)
            {
                return;
            }



            string temp = DateTime.Now.ToString("HH:mm:ss.fff") + "\r\n" + r + "\r\n";

            using (StringReader sr = new StringReader(r))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    // do something
                    ///
                    if (line.Contains("UniSDK AsrOnlineText") ||
                        line.Contains("UniSDK AsrOfflineTest") ||
                        line.Contains("UniSDK WakeupWord"))
                    {
                        var splits = line.Split(':');
                        if (splits.Count() == 1)
                        {
                            splits = line.Split('=');
                        }
                        var re = ResultManager.PenddingResult;
                        if (re == null)
                        {
                            re = new TestResult();
                        }
                        re.TestDate = DateTime.Now.ToString("yyy-MM-dd HH:mm:ss");
                        re.Recognition = splits[1];
                        re.RecognitionTime = DateTime.Now;

                        if (string.IsNullOrEmpty(re.Audio))
                        {
                            if (testMode) // 人工
                            {
                                // ResultManager.ArtificialResults.Add(re);
                                re.DistanceText = ParameterManager.ArDistanceText;
                                re.AngelText = ParameterManager.ArAngelText;
                                re.NoiseText = ParameterManager.ArNoiseText;
                            }
                            else
                            {
                                //ResultManager.RecordResults.Add(re);
                                re.DistanceText = ParameterManager.ReDistanceText;
                                re.AngelText = ParameterManager.ReAngelText;
                                re.NoiseText = ParameterManager.ReNoiseText;
                            }
                        }


                        if (!string.IsNullOrEmpty(re.AudioCommand) &&
                            re.Recognition.Trim() == re.AudioCommand.Trim())
                        {
                            re.Result = Result.Success;
                        }
                        else
                        {
                            re.Result = Result.Fail;
                            //ProjectManager.SetWaitHandle();
                            //ResultManager.PenddingResult = null;
                        }
                        //if (re.Recognition.Trim() == Constant.Wakeupwork)
                        //{
                        //    ProjectManager.SetWaitHandle();
                        //    ResultManager.PenddingResult = null;
                        //}
                        ResultManager.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                        {
                            if (string.IsNullOrEmpty(re.Audio))
                            {
                                if (testMode) // 人工
                                {
                                    ResultManager.ArtificialResults.Add(re);
                                }
                                else
                                {
                                    ResultManager.RecordResults.Add(re);
                                }
                            }
                            else
                            { ResultManager.ResultItems.Add(re); }
                            ResultManager.PenddingResult = null;

                        }));
                        //todo 对结果进行

                       

                       // break;
                    }

                    if (line.Contains("UniSDK tts end success") //line.Contains("UniSDK AsrOnlineSemantic")
                        )
                    {
                        //System.Threading.Thread.Sleep(3000);
                        BackgroundWorker bg = new BackgroundWorker();
                        bg.DoWork += (bgs, bge) =>
                        {
                            System.Threading.Thread.Sleep(ParameterManager.VoiceDelay * 1000);
                           
                            ProjectManager.SetWaitHandle();
                            ResultManager.PenddingResult = null;
                        };
                        bg.RunWorkerAsync();
                    }

                    if (line.Contains(Constant.NetworkOK))
                    {
                        NetworkStatusManager.NetworkStatus = true;
                    }

                    if (line.Contains(Constant.NetworkNotOK))
                    {
                        NetworkStatusManager.NetworkStatus = false;
                    }

                    //if ()
                    //{
                    //    var splits = line.Split(':');
                    //    break;
                    //}
                }
            }

            if (!string.IsNullOrEmpty(ReceiveText) && ReceiveText.Length > 512 * 1024)
            {
                ReceiveText = string.Empty;
            }
            ReceiveText += temp;

            SerialPortHelper.SerialPortString.Append(temp);


            try
            {
                rport.DiscardInBuffer();
            }
            catch (Exception)
            {

            }

        }



        public DelegateCommand OpenSerialPortCommand { get; set; }
        public DelegateCommand CloseSerialPortCommand { get; set; }
        public DelegateCommand ExcelTestCommand { get; set; }
        public DelegateCommand ResultToExcelCommand { get; set; }
        public DelegateCommand SoundTestCommand { get; set; }

        public DelegateCommand ProjectCommand { get; set; }

        public DelegateCommand SendCommand { get; set; }
        public DelegateCommand OpenSendCommand { get; set; }
        public DelegateCommand CloseSendCommand { get; set; }

        public DelegateCommand StartRecordCommand { get; set; }
        public DelegateCommand StopRecordCommand { get; set; }
        public DelegateCommand PortTestCommand { get; set; }

        public DelegateCommand RecordCommand { get; set; }

        public DelegateCommand RefreshSerialPortCommand { get; set; }

        public DelegateCommand PlayProjectCommand { get; set; }
        public DelegateCommand StopProjectCommand { get; set; }
        public DelegateCommand ClearTextCommand { get; set; }

        public DelegateCommand SaveTextCommand { get; set; }

        public DelegateCommand NetworkStatusCommand { get; set; }

        public DelegateCommand ClearResultCommand { get; set; }

        public DelegateCommand ArtificialCommand { get; set; }

        public DelegateCommand ClearProjectCommand { get; set; }

        public DelegateCommand SatResultCommand { get; set; }
        public DelegateCommand PauseProjectCommand { get; set; }
        public DelegateCommand ParameterCommand { get; set; }

        #endregion

        private void Init()
        {
            SerialPorts = SerialPortHelper.Instance.GetPortNames();
            BaudRateSource = new ObservableCollection<int>();
            BaudRateSource.Add(115200);
            BaudRateSource.Add(9600);
            BaudRateSource.Add(4800);
            BaudRateSource.Add(2400);
            BaudRateSource.Add(1200);

            StopBitsSource = new ObservableCollection<StopBits>(Enum.GetValues(typeof(StopBits)).Cast<StopBits>());

            ParitySource = new ObservableCollection<Parity>(Enum.GetValues(typeof(Parity)).Cast<Parity>());

            DataBitSource = new ObservableCollection<int>();
            DataBitSource.Add(8);
            DataBitSource.Add(7);
            DataBitSource.Add(6);
            DataBitSource.Add(5);


            EncodingSource = new ObservableCollection<string>() { "UTF-8", "UNICODE", "GB2312", "UTF-32", "ASCII" };


            //---------------------初始化选项
            if (SerialPorts.Count > 0)
            {
                SelectedPort = SerialPorts[0];
                SelectedSendPort = SerialPorts[0];
            }
            SelectedBaudRate = 115200;
            SelectedDataBit = 8;
            SelectedStopBit = StopBits.One;
            SelectedParity = Parity.None;
            SelectedEncoding = "UTF-8";
            loopTimes = ParameterManager.LoopTimes.ToString();

            ProjectManager.PlayProjectDone += new EventHandler(ProjectManager_PlayProjectDone);
            ProjectManager.LeftPlayTimeChanged += ProjectManager_LeftPlayTimeChanged;
            SetNetworkRecord();
            DispatcherTimer dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal, App.Current.Dispatcher);
            dispatcherTimer.Interval = new TimeSpan(0, 15, 0);
            dispatcherTimer.Tick += DispatcherTimer_Tick;
            dispatcherTimer.Start();

        }

        private void SetNetworkRecord()
        {
            NetworkStatusManager.Records.Add(new NetworkStatusRecord()
            {
                Time = DateTime.Now,
                Status = NetworkStatusManager.NetworkStatus == null ? "未知" : NetworkStatusManager.NetworkStatus.Value ? "正常" : "断开"
            });
        }

        private void DispatcherTimer_Tick(object sender, EventArgs e)
        {
            SetNetworkRecord();
        }

        void ProjectManager_LeftPlayTimeChanged(object sender, EventArgs e)
        {
            LeftPlayTimes = ProjectManager.LeftPlayTime;
        }

        void ProjectManager_PlayProjectDone(object sender, EventArgs e)
        {
            IsPlayProjectEnabled = true;
            IsStopProjectEnabled = false;
        }



        #region 串口设置
        private Visibility portTestVisibility = Visibility.Collapsed;

        public Visibility PortTestVisibility
        {
            get { return portTestVisibility; }
            set { portTestVisibility = value; RaisePropertyChanged("PortTestVisibility"); }
        }


        private ObservableCollection<string> serialPorts;
        /// <summary>
        /// 串口名数据源
        /// </summary>
        public ObservableCollection<string> SerialPorts
        {
            get { return serialPorts; }
            private set
            {
                serialPorts = value;
                RaisePropertyChanged("SerialPorts");
            }
        }

        private string selectedPort;
        public string SelectedPort
        {
            get { return selectedPort; }
            set
            {
                selectedPort = value;
                RaisePropertyChanged("SelectedPort");
            }
        }



        private ObservableCollection<int> baudRateSource;
        /// <summary>
        /// 波特率数据源
        /// </summary>
        public ObservableCollection<int> BaudRateSource
        {
            get { return baudRateSource; }
            private set
            {
                baudRateSource = value;
                RaisePropertyChanged("BaudRateSource");
            }
        }

        private int selectedBaudRate;
        public int SelectedBaudRate
        {
            get { return selectedBaudRate; }
            set
            {
                selectedBaudRate = value;
                RaisePropertyChanged("SelectedBaudRate");
            }
        }


        private ObservableCollection<int> dataBitSource;
        /// <summary>
        /// 数据位数据源
        /// </summary>
        public ObservableCollection<int> DataBitSource
        {
            get { return dataBitSource; }
            private set
            {
                dataBitSource = value;
                RaisePropertyChanged("DataBitSource");
            }
        }

        private int selectedDataBit;
        public int SelectedDataBit
        {
            get { return selectedDataBit; }
            set
            {
                selectedDataBit = value;
                RaisePropertyChanged("SelectedDataBit");
            }
        }



        private ObservableCollection<StopBits> stopBitsSource;
        /// <summary>
        /// 停止位数据源
        /// </summary>
        public ObservableCollection<StopBits> StopBitsSource
        {
            get { return stopBitsSource; }
            set
            {
                stopBitsSource = value;
                RaisePropertyChanged("StopBitsSource");
            }
        }

        private StopBits selectedStopBit;
        public StopBits SelectedStopBit
        {
            get { return selectedStopBit; }
            set
            {
                selectedStopBit = value;
                RaisePropertyChanged("SelectedStopBit");
            }
        }


        private ObservableCollection<Parity> paritySource;
        /// <summary>
        /// 奇偶检验方式
        /// </summary>
        public ObservableCollection<Parity> ParitySource
        {
            get { return paritySource; }
            set
            {
                paritySource = value;
                RaisePropertyChanged("ParitySource");
            }
        }

        private Parity selectedParity;
        public Parity SelectedParity
        {
            get { return selectedParity; }
            set
            {
                selectedParity = value;
                RaisePropertyChanged("SelectedParity");
            }
        }

        private ObservableCollection<string> encodingSource;
        /// <summary>
        /// 串口编码
        /// </summary>
        public ObservableCollection<string> EncodingSource
        {
            get { return encodingSource; }
            private set
            {
                encodingSource = value;
                RaisePropertyChanged("EncodingSource");
            }
        }

        private string selectedEncoding;
        public string SelectedEncoding
        {
            get { return selectedEncoding; }
            set
            {
                selectedEncoding = value;
                RaisePropertyChanged("SelectedEncoding");
            }
        }

        private bool isPortOpening = false;

        public bool IsPortOpening
        {
            get { return isPortOpening; }
            set { isPortOpening = value; RaisePropertyChanged("IsPortOpening"); }
        }

        private string selectedSendPort;

        public string SelectedSendPort
        {
            get { return selectedSendPort; }
            set { selectedSendPort = value; RaisePropertyChanged("SelectedSendPort"); }
        }

        private string sendOpenText = "否";

        public string SendOpenText
        {
            get { return sendOpenText; }
            set { sendOpenText = value; RaisePropertyChanged("SendOpenText"); }
        }

        private bool isSendPortOpening = false;

        public bool IsSendPortOpening
        {
            get { return isSendPortOpening; }
            set { isSendPortOpening = value; RaisePropertyChanged("IsSendPortOpening"); }
        }

        private string sendText;
        public string SendText
        {
            get { return sendText; }
            set
            {
                sendText = value;
                RaisePropertyChanged("SendText");
            }
        }

        private string receiveText;

        public string ReceiveText
        {
            get { return receiveText; }
            set { receiveText = value; RaisePropertyChanged("ReceiveText"); }
        }


        #endregion

        #region 语音库
        private ObservableCollection<Sound> soundsSource;
        public ObservableCollection<Sound> SoundsSource
        {
            get { return soundsSource; }
            set
            {
                soundsSource = value;
                RaisePropertyChanged("SoundsSource");
            }
        }

        private ObservableCollection<Sound> fullSoundsSource;
        private string keyword;

        public string Keyword
        {
            get { return keyword; }
            set
            {
                keyword = value;
                RaisePropertyChanged("Keyword");
                if (fullSoundsSource != null)
                {
                    SoundsSource = new ObservableCollection<Sound>(fullSoundsSource.Where(s => { return s.DisplayText.Contains(Keyword); }));
                }
            }
        }

        #endregion

        private string loopTimes;
        public string LoopTimes
        {
            get { return loopTimes; }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    int i = 0;
                    if (int.TryParse(value, out i))
                    {
                        ParameterManager.LoopTimes = i;
                    }
                    else
                    {
                        App.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                        {
                            RaisePropertyChanged("LoopTimes");
                        }));
                        return;
                    }
                }
                loopTimes = value;
                RaisePropertyChanged("LoopTimes");
            }
        }

        private int leftPlayTimes;

        public int LeftPlayTimes
        {
            get { return leftPlayTimes; }
            set { leftPlayTimes = value; RaisePropertyChanged("LeftPlayTimes"); }
        }


        //private string leftTimes;
        //public string LeftTimes
        //{
        //    get { return leftTimes; }
        //    set
        //    {

        //        RaisePropertyChanged("LeftTimes");
        //    }
        //}

        private bool isPlayProjectEnabled = true;

        public bool IsPlayProjectEnabled
        {
            get { return isPlayProjectEnabled; }
            set { isPlayProjectEnabled = value; RaisePropertyChanged("IsPlayProjectEnabled"); }
        }

        private bool isStopProjectEnabled = false;

        public bool IsStopProjectEnabled
        {
            get { return isStopProjectEnabled; }
            set { isStopProjectEnabled = value; RaisePropertyChanged("IsStopProjectEnabled"); }
        }


        private bool isPauseProjectEnabled = false;

        public bool IsPauseProjectEnabled
        {
            get { return isPauseProjectEnabled; }
            set { isPauseProjectEnabled = value; RaisePropertyChanged("IsPauseProjectEnabled"); }
        }

        #region IDropTarget Members
        DefaultDropHandler t = new DefaultDropHandler();
        public void DragOver(IDropInfo dropInfo)
        {


            if (dropInfo.Data is IDataObject)
            {
                var files = (string[])(dropInfo.Data as IDataObject).GetData(DataFormats.FileDrop);
                if (files != null)
                {
                    dropInfo.DropTargetAdorner = DropTargetAdorners.Insert;
                    dropInfo.Effects = DragDropEffects.Copy;
                }
            }
            else
            {
                t.DragOver(dropInfo);
            }

        }

        public void Drop(IDropInfo dropInfo)
        {
            if (dropInfo.Data is IDataObject)
            {
                var files = (string[])(dropInfo.Data as IDataObject).GetData(DataFormats.FileDrop);
                if (files != null)
                {
                    foreach (var item in files)
                    {
                        if (((File.GetAttributes(item) & FileAttributes.Directory) == FileAttributes.Directory))
                        {
                            string[] sounds = Directory.GetFiles(item, "*.wav", SearchOption.AllDirectories);
                            if (sounds != null)
                            {
                                int fIndex = dropInfo.InsertIndex;
                                foreach (var sou in sounds)
                                {
                                    ProjectManager.InsertProjectItem(fIndex,
                                   new ProjectItem(new Sound() { Path = sou, DisplayText = Path.GetFileName(sou) }));
                                    fIndex++;
                                }
                            }
                        }
                        else
                        {
                            if (Path.GetExtension(item) == ".wav")
                            {
                                ProjectManager.InsertProjectItem(dropInfo.InsertIndex,
                                    new ProjectItem(new Sound() { Path = item, DisplayText = Path.GetFileName(item) }));
                            }
                        }
                    }

                }
            }
            else
            {
                t.Drop(dropInfo);

            }
        }

        #endregion
    }
}
